import { Vec3 } from "cc";
import { _decorator } from "cc";
import { UITransform } from "cc";
import { v2 } from "cc";
import { tween } from "cc";
import { v3 } from "cc";
import { Vec2 } from "cc";
import { EventTouch } from "cc";
import { NodeEventType } from "cc";
import { Component } from "cc";
const { ccclass, property } = _decorator;

/**
 * 拖拽组件
 */
@ccclass('JNodeDrag')
export default class JNodeDrag extends Component{
    
    //原始位置
    original:Vec3;

    //开始接触时候的位置
    startTouchPos:Vec3;

    //是否拖拽了
    isMove:boolean = false;

    //是否触摸
    isTouch:boolean = false;

    //添加移动回调
    moveFuns:Function[] = [];

    //添加移动结束回调
    moveEndFuns:Function[] = [];

    addMoveEvent(fun:Function){
        this.moveFuns.push(fun);
    }
    addMoveEndEvent(fun:Function){
        this.moveEndFuns.push(fun);
    }
    
    onLoad(){
        this.original = this.original || this.node.position.clone();
        //添加拖拽事件
        this.node.on(NodeEventType.TOUCH_START,this.onTouchStart,this);
        this.node.on(NodeEventType.TOUCH_MOVE,this.onTouchMove,this);
        this.node.on(NodeEventType.TOUCH_END,this.onTouchEnd,this);
        this.node.on(NodeEventType.TOUCH_CANCEL,this.onTouchEnd,this);
    }

    //传入UI位置返回位置
    getPosition(ui:Vec2):Vec2{
        return Object.assign(v2(),this.node.parent.getComponent(UITransform).convertToNodeSpaceAR(v3(ui.x, ui.y)));
    }

    //触摸开始
    onTouchStart(){

        this.startTouchPos = this.node.position.clone();

        this.isMove = false;
        this.isTouch = true;

    }
    //触摸移动
    onTouchMove(e:EventTouch){

        let start = this.getPosition(e.getUIStartLocation());
        let move = this.getPosition(e.getUILocation());

        //移动了标记移动了
        if(!(e.getUIStartLocation().equals(e.getUILocation()))) this.isMove = true;

        let diff = move.subtract(start);
        this.node.position = this.startTouchPos.clone().add(v3(diff.x,diff.y,0));

        //移动事件通知
        this.moveFuns.forEach(fun => fun(e))

    }

    //触摸结束
    onTouchEnd(e:EventTouch){

        console.log("触摸结束");

        this.isTouch = false;

        //结束之后回到原始位置
        this.onReturnAnim();

        //移动结束通知
        this.moveEndFuns.forEach(fun => fun(e))

    }

    onReturnAnim(){
        if(this.isTouch) return;
        //回到原始位置
        tween(this.node)
            .to(.25,{position:this.original})
            .start();
    }

    //更新原始点
    onUpdateOriginal(original:Vec3){

        if(this.original.equals(original)) return;
        this.original = original;
        this.onReturnAnim();

    }

}


